<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>announcement</title>
    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div style="text-align: center">
    <h3>公告通知</h3>
    <textarea id="chat-log" rows="10" cols="100"></textarea>
    <br>
    <input id="chat-message-submit" type="button" value="发 送">
</div>
<script>
    const chatSocket = new WebSocket('ws://' + window.location.host + '/ws/announcement');
    {# 接收数据 #}
    chatSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        {#console.log(data);#}
        if (data.code === 3000) {
            alert(data.message);
        } else {
            document.querySelector('#chat-log').value += (
                data.data.promulgator + '\n' +
                data.data.title + '\n' +
                data.data.content + '\n\n'
            );
        }
    };
    {# 关闭时触发 #}
    chatSocket.onclose = function (e) {
        console.log(e);
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-submit').onclick = function (e) {
        {# 发送数据到websocket服务端 #}
        chatSocket.send(JSON.stringify({
            'code': 1000,
            'message': '有没有通知？'
        }));
    }

    $(function () {
        $.ajax({
            //请求方式
            type: "GET",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url: "http://127.0.0.1:8000/announcements",
            //请求成功
            success: function (result) {
                result.forEach(function (data) {
                    {#console.log(data)#}
                    $('#chat-log').append(
                        data.title + '\n' +
                        data.content + '\n\n'
                    );
                });
            },
            //请求失败，包含具体的错误信息
            error: function (e) {
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    });

</script>
</body>
</html>